<template>
  <a-modal
    v-model:visible="visible"
    title="新建转化追踪"
    :width="600"
    :destroyOnClose="true"
    @ok="handleAddConversion"
    :confirmLoading="loading"
  >
    <a-form :model="formState" :rules="rules" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="账号" name="accountId">
        <a-select v-model:value="formState.accountId" placeholder="请选择账号" style="width: 100%">
          <a-select-option v-for="account in AccountItems" :key="account._id" :value="account._id">
            {{ account.Name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="目标" name="source">
        <a-radio-group v-model:value="formState.source">
          <a-radio-button :value="1">App</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="转化名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入转化名称，最多50字" :maxlength="50" show-count />
      </a-form-item>

      <a-form-item label="转化类型" name="type">
        <a-select v-model:value="formState.type" placeholder="请选择转化类型" style="width: 100%" @change="onTypeChange">
          <a-select-option v-for="(item, key) in ConversionType" :key="key" :value="Number(key)">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="APPID" name="appId">
        <a-input-number v-model:value="formState.appId" placeholder="请输入APPID" style="width: 100%" :min="1" />
      </a-form-item>

      <a-form-item label="转化方案" name="trackingType">
        <a-radio-group v-model:value="formState.trackingType">
          <a-radio v-if="isTrackingTypeVisible(1)" :value="1">API统计方案</a-radio>
          <a-radio v-if="isTrackingTypeVisible(2)" :value="2">API上报方案</a-radio>
          <a-radio v-if="isTrackingTypeVisible(3)" :value="3">小米数据</a-radio>
          <a-radio v-if="isTrackingTypeVisible(4)" :value="4">JS埋点</a-radio>
          <a-radio v-if="isTrackingTypeVisible(5)" :value="5">线索API上报</a-radio>
          <a-radio v-if="isTrackingTypeVisible(6)" :value="6">小米商店数据</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";

import { ConversionType, ConversionForm, ConversionTypeMap } from "@/pages/NewBatchCreateAd/adx/xiaomi/enum";
import { addConversion } from "@/api/adx-tool";

import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
const store = batchCreateAdStore();

const { AccountItems } = store;

// 定义事件
const emit = defineEmits(["success"]);

// 表单相关
const formRef = ref();
const visible = ref(false);
const loading = ref(false);

// 表单数据
const formState = reactive<ConversionForm>({
  accountId: null,
  name: "",
  source: 1,
  type: 1,
  appId: "",
  trackingType: 1,
});

// 表单验证规则
const rules = {
  accountId: [{ required: true, message: "请选择账号" }],
  name: [{ required: true, message: "请输入转化名称" }],
  type: [{ required: true, message: "请选择转化类型" }],
  appId: [{ required: true, message: "请输入APPID" }],
  trackingType: [{ required: true, message: "请选择转化方案" }],
};

// 显示弹窗
const show = () => {
  // 重置表单
  resetForm();

  // 显示弹窗
  visible.value = true;

  // 初始化后确保转化方案正确
  onTypeChange();
};

// 重置表单
const resetForm = () => {
  formState.accountId = null;
  formState.name = "";
  formState.type = 1;
  formState.appId = "";
  formState.trackingType = 1;

  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理新建转化追踪
const handleAddConversion = async () => {
  const validate = await formRef.value.validate();

  if (validate) {
    try {
      loading.value = true;
      const sentData = {
        accountId: formState.accountId, // 修改为 AccountId 以匹配接口定义
        input: {
          appId: [formState.appId],
          name: formState.name,
          source: formState.source,
          type: formState.type,
          trackingType: formState.trackingType,
        },
      };
      const res = await addConversion(sentData);
      if (!res) {
        message.error("转化追踪创建失败，请检查是否已存在相同名称的转化追踪");
      }
      if (res && res[0]) {
        if (res[0].conversionName === formState.name + "(0)") {
          message.success("转化追踪创建成功");
        } else {
          message.info("已存在相同类型转化追踪：" + res[0].conversionName);
        }
      }
      visible.value = false; // 成功后关闭弹窗
    } catch (error) {
      message.error("创建转化追踪失败，请检查是否已存在相同名称的转化追踪");
    } finally {
      loading.value = false;
    }
  }
};

// 暴露方法给父组件
defineExpose({
  show,
  resetForm,
});

// 添加新的计算属性
const isTrackingTypeVisible = (type: number) => {
  // 根据转化类型返回是否可见
  return ConversionTypeMap[type].includes(formState.type);
};

// 监听转化类型变化
const onTypeChange = () => {
  // 遍历所有转化方案，找到第一个支持当前转化类型的方案设置为默认方案
  for (const key in ConversionTypeMap) {
    if (ConversionTypeMap[key].includes(formState.type)) {
      formState.trackingType = Number(key);
      break;
    }
  }
};

// 添加 watch 监听转化类型变化
watch(
  () => formState.type,
  () => {
    onTypeChange();
  }
);
</script>
